package com.itheima.service.store.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.store.CompanyDao;
import com.itheima.domain.store.Company;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.CompanyService;
import com.itheima.utils.UUIDUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class CompanyServiceImpl implements CompanyService {
    @Override
    public PageInfo<Company> queryPage(Integer pageNum, Integer pageSize) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CompanyDao companyDao = sqlSession.getMapper(CompanyDao.class);
        PageHelper.startPage(pageNum,pageSize);
        List<Company> companies = companyDao.findAll();
        PageInfo<Company> pageInfo = new PageInfo<>(companies);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public List<Company> findAll() throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CompanyDao companyDao = sqlSession.getMapper(CompanyDao.class);
        List<Company> companies = companyDao.findAll();
        sqlSession.close();
        return companies;
    }

    @Override
    public Company findById(String id) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CompanyDao companyDao = sqlSession.getMapper(CompanyDao.class);
        Company company = companyDao.findById(id);
        sqlSession.close();
        return company;
    }

    @Override
    public void save(Company company) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CompanyDao companyDao = sqlSession.getMapper(CompanyDao.class);
        company.setId(UUIDUtil.getSimpleUUID());
        companyDao.save(company);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void deleteById(String... ids) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CompanyDao companyDao = sqlSession.getMapper(CompanyDao.class);
        for (String id : ids) {
            companyDao.deleteById(id);
        }
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void update(Company company) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CompanyDao companyDao = sqlSession.getMapper(CompanyDao.class);
        companyDao.update(company);
        sqlSession.commit();
        sqlSession.close();
    }
}
